package br.com.ava.core.infra.mail;

import org.apache.commons.mail.MultiPartEmail;

import br.com.ava.core.ConstantesMensagens;
import br.com.ava.core.configuracao.ConfiguracaoConverter;
import br.com.ava.core.configuracao.ConstantesConfiguracoes;
import br.com.ava.core.infra.excecao.NegocioException;

/**
 * Classe utilit�ria para envio de e-mail.
 */
public class EMailUtil {

	private static EMailUtil instance;

	private EMailUtil() {
		// Apenas para n�o deixar construir.
	}

	public static synchronized EMailUtil getInstance() {
		if (instance == null) {
			instance = new EMailUtil();
		}
		return instance;
	}

	public static void setInstance(EMailUtil eMailUtil) {
		instance = eMailUtil;
	}

	public void enviar(String host, String from, String[] to, String subject,
			String text) {
		try {
			MultiPartEmail email = new MultiPartEmail();
			email.setHostName(host);
			email.setFrom(from, from);
			email.setSubject(subject);

			for (String dest : to) {
				email.addTo(dest);
			}
			email.setMsg(text);
			email.setTLS(true);
			email.setSmtpPort(Integer.valueOf(
					ConfiguracaoConverter.getInstance().getAsString(
							ConstantesConfiguracoes.EMAIL_PORTA)).intValue());

			// TODO Remover c�digo depois dos testes com o servidor do gmail.
			// -- CONFIGURACAO GMAIL ---
			email.setSSL(true);
			email.setAuthentication("teste", "XXXX");
			// --------------------------

			email.send();
		} catch (Exception e) {
			throw new NegocioException(
					ConstantesMensagens.MSG_ERRO_ENVIO_EMAIL, e);
		}
	}

}